import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { Money } from './entities/money.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateMoneyDto } from './dto/create-money.dto';
import { UpdateMoneyDto } from './dto/update-money.dto';
import { UserService } from '../../admin/user/user.service';

@Injectable()
export class MoneyService {
  constructor(
    @Inject(forwardRef(() => UserService))
    private userService: UserService,
    @InjectRepository(Money)
    private moneyRepository: Repository<Money>,
  ) {}
  create(createMoneyDto: CreateMoneyDto) {
    return this.moneyRepository.save(createMoneyDto);
  }

  async findAll(userId: number) {
    const user = await this.userService.getWithMoney(userId);
    if (user) {
      return user.moneys;
    } else {
      throw new Error('获取用户货币数据失败');
    }
  }

  findOne(id: number) {
    return this.moneyRepository.findOneByOrFail({ id });
  }

  async update(id: number, updateMoneyDto: UpdateMoneyDto) {
    return this.moneyRepository.update({ id }, updateMoneyDto);
  }

  remove(id: number) {
    return this.moneyRepository.softDelete({ id });
  }

  /**
   * 每日签到获取7W点券
   * @param userId
   */
  async sign(userId: number) {
    const money = await this.moneyRepository.findOneBy({
      user: { id: userId },
      priceType: 2,
    });
    money.num += 70000;
    await this.moneyRepository.save(money);
  }
}
